<?php

# Jisko Python Library: to interact with the Jisko API
# Copyright (C) 2008 Carlos Hellin <charlie@charli.es>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

// This module requires the Curl PHP module, available in PHP 4 and 5
assert(function_exists("curl_init"));

class Jisko {
	//Creates a new Jisko session for the given user.
	function Jisko($auth_nickname=null, $auth_key=null) {
		$this->auth_nickname = $auth_nickname;
		$this->auth_key = $auth_key;
	}

	//Get the notes of the identified user.
	function fetch_archive() {
		return $this->fetch("/getFriends");
	}

	//Get the notes from the public timeline.
	function fetch_public() {
		return $this->fetch("/getPublic");
	}

	//Get the timeline of persons who follows the identified user.
	function fetch_friends() {
		return $this->fetch("/getFriends");
	}

	//Get the private notes of the identified user.
	function fetch_private() {
		return $this->fetch("/getPrivate");
	}

	//Get the replies of the user of the identified user.
	function fetch_replies() {
		return $this->fetch("/getReplies");
	}

	//Get the notes marked as favorites by the identified user.
	function fetch_favorites() {
		return $this->fetch("/getFavorites");
	}

	//Update the status by sending a note. To ship to Twitter, use twitter=1
	function update_status($note, $twitter=0) {
		$result = $this->fetch("/updateStatus", null, array(
			"note" => $note,
			"twitter" => $twitter
		));
		return $result;
    	}

	function fetch($uri, $url_args=null, $post_args=null) {
		if (!$url_args) $url_args = array();
		$pairs = array();
		foreach ($url_args as $name => $value) {
			$pairs[] = $name . "=" . urlencode($value);
		}
		$url = "http://jisko.net/api" . $uri . "?format=json" . join("&", $pairs);
		
		$curl = curl_init("jisko.net");
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		if ($this->auth_nickname && $this->auth_key) {
			curl_setopt($curl, CURLOPT_USERPWD,
				$this->auth_nickname . ":" . $this->auth_key);
			curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		}
		if ($post_args) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $post_args);
		}
		$response = curl_exec($curl);
		$info = curl_getinfo($curl);
		curl_close($curl);
		if ($info["http_code"] != 200) {
			return null;
		}
		return json_decode($response);
	}
}
